package com.ipad.view.dialog;

import android.Manifest;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.ipad.R;
import com.ipad.net.entity.ObjectVo;
import com.ipad.net.presenter.upload.UploadContract;
import com.ipad.net.presenter.upload.UploadPresenter;
import com.ipad.ui.BaseActivity;
import com.ipad.utils.OkHttpUtils;
import com.ipad.utils.SharePerenceUtils;
import com.ipad.utils.ToasUtils;
import com.unco.library.PainterView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Administrator on 2019/4/10.
 */

public class SignDialog extends DialogFragment implements UploadContract.View {
    @BindView(R.id.sign_view)
    PainterView sign_view;
    @BindView(R.id.delivery_warehouse)
    TextView delivery_warehouse;
    @BindView(R.id.dialog_sign_clear)
    Button dialog_sign_clear;
    @BindView(R.id.dialog_sign_cancle)
    Button dialog_sign_cancle;
    @BindView(R.id.dialog_sign_confirm)
    Button dialog_sign_confirm;

    String signName = "";
    String id = "";
    String billCode = "";
    String container = "";
    UploadPresenter uploadPresenter;

    BaseActivity baseActivity;
    private String TAG = "signDialog";
    Map<String, RequestBody> map;

    public static SignDialog newInstance(String signName, String id,String container,String billCode) {
        Bundle args = new Bundle();
        args.putString("sign_name", signName);
        args.putString("id", id);
        SignDialog fragment = new SignDialog();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NO_TITLE, R.style.loading_style);
    }

    @Override
    public void onStart() {
        super.onStart();
        WindowManager.LayoutParams attributes = getDialog().getWindow().getAttributes();
        attributes.width = getResources().getDisplayMetrics().widthPixels / 3 * 2;
        attributes.height = getResources().getDisplayMetrics().heightPixels / 3 * 2;
        getDialog().setCanceledOnTouchOutside(true);
        getDialog().getWindow().setAttributes(attributes);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.dialog_sign, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        baseActivity = (BaseActivity) getActivity();

        signName = getArguments().getString("sign_name");
        id = getArguments().getString("id");
        container = getArguments().getString("container");
        billCode = getArguments().getString("billCode");

        uploadPresenter = new UploadPresenter();
        uploadPresenter.attachView(this);

        dialog_sign_clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sign_view.clear();
            }
        });

        dialog_sign_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveFile(signName);
            }
        });

        dialog_sign_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });

    }


    public void saveFile(String str) {

        map = new HashMap<>();

        sign_view.setBackgroundResource(R.color.white);
        Bitmap bitmap = sign_view.creatBitmap();
//        int width = bitmap.getWidth();
//        int height = bitmap.getHeight();
//        Matrix matrix = new Matrix();
//        matrix.postScale(0.5f, 0.5f);
//        Bitmap bitmap1 = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);


        String path = "/sdcard/heyi_sign/";
        String fileName = str + ".png";
        File file = new File(path);
        File file2 = new File(path + fileName);
        if (!file.exists()) {
            file.mkdir();
        }

        try {
            file2.createNewFile();
            FileOutputStream fileOutputStream = new FileOutputStream(file2);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
            bitmap.recycle();
//            bitmap1.recycle();
//                Toast.makeText(getActivity(),"保存成功",Toast.LENGTH_SHORT).show();
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file2);
            map.put("file\";filename=\"" + fileName, requestBody);
            uploadPresenter.upload(map, id, container, billCode, SharePerenceUtils.getToken(getContext()));

        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getActivity(), "保存失败", Toast.LENGTH_SHORT).show();

        }

    }


    @Override
    public void stopLoading() {
        baseActivity.dismissDialog();
    }

    @Override
    public void loading(String msg) {
        baseActivity.showDialog(msg);
    }

    @Override
    public void error(String msg) {
        ToasUtils.getToast(msg, getActivity());
    }

    @Override
    public void uploadSuccess(ObjectVo o) {
        if (o != null) {
            if (o.getCode() == 200) {
                ToasUtils.getToast("上传成功", getActivity());
            } else {
                ToasUtils.getToast(o.getMessage(), getActivity());
            }

            dismiss();
        }

    }
}
